﻿using System;
using System.Web;
using System.IO;
using System.Net;

namespace SBPweb.Relay.Processor
{

    public class ContextProcessor
    {

        #region Private fields

        private HttpContext context;
        private Uri baseUri;
        private CookiedWebClient client;

        #endregion

        #region Constructor logic

        public ContextProcessor(HttpContext context, Uri baseUri)
        {
            this.context = context;
            this.baseUri = baseUri;
            InitializeClient();
        }

        #endregion

        #region Methods

        public void Process()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(GetRelayedUri(context.Request.Url, baseUri));
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            WebResponseCloneHelper cloner = new WebResponseCloneHelper(new WebResponseCloneHelper.ProcessOutputHandler(ProcessOutput));
            cloner.DeepCopy(response, context.Response);
        }
        
        #region Private helper functions

        protected internal void InitializeClient()
        {
            client = new CookiedWebClient();
            client.ProcessedAddress = GetRelayedUri(context.Request.Url, baseUri);
        }

        protected internal Uri GetRelayedUri(Uri originalUri, Uri newBaseUri)
        {
            UriBuilder builder = new UriBuilder(newBaseUri.Scheme, newBaseUri.Host, newBaseUri.Port, originalUri.AbsolutePath);
            return builder.Uri;
        }

        protected internal string ProcessOutput(string output)
        {
            string from = baseUri.AbsoluteUri;
            string to = context.Request.Url.OriginalString;
            to = to.Substring(0, to.IndexOf(context.Request.Url.LocalPath) + 1);
            return output.Replace(from, to);
        }

        #endregion

        #endregion

    }

}